<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('公司基本信息') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('公司全称')" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          :placeholder="$t('公司全称')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('公司简称')" prop="companyShortName">
        <el-input
          v-model="queryParams.companyShortName"
          :placeholder="$t('公司简称')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('项目状态')" prop="dealStatus">
        <dictSelect
          v-model="queryParams.dealStatus"
          dictionary="deal_status"
          :clearable="true"
        />
      </el-form-item>
      <el-form-item :label="$t('一级行业')" prop="industryFirst">
        <el-select v-model="queryParams.industryFirst" filterable :placeholder="$t('一级行业')">
          <el-option
            v-for="si in industryFirstOptions"
            :key="si.id"
            :label="$t(si.name)"
            :value="si.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" tooltip-effect="darkTable" :data="companyBaseList" border>
      <el-table-column :label="$t('公司全称')" prop="companyName" :show-overflow-tooltip="true" fixed="left" width="250">
        <template slot-scope="scope">
          <router-link
            target="_blank"
            :to="{path:'/company/base/companyBaseHome',query:{companyId:scope.row.id, source: source }}"
            class="link_a"
          >{{ scope.row.companyName }}</router-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('公司简称')" align="center" prop="companyShortName" show-overflow-tooltip width="200" />
      <el-table-column :label="$t('法人代表')" align="center" prop="legalPerson" show-overflow-tooltip min-width="120" />
      <el-table-column :label="$t('一级行业')" align="center" prop="industryFirstLabel" show-overflow-tooltip min-width="160">
        <template slot-scope="scope">
          <span>{{ $t(scope.row.industryFirstLabel) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('二级行业')" align="center" prop="industrySecondLabel" show-overflow-tooltip min-width="160">
        <template slot-scope="scope">
          <span>{{ $t(scope.row.industrySecondLabel) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('注册省')" align="center" prop="provinceRegisteredLabel" show-overflow-tooltip min-width="90">
        <template slot-scope="scope">
          <span>{{ $t(scope.row.provinceRegisteredLabel) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('注册市')" align="center" prop="cityRegisteredLabel" show-overflow-tooltip width="90">
        <template slot-scope="scope">
          <span>{{ $t(scope.row.cityRegisteredLabel) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('注册资本') + $t('金额单位')" align="center" show-overflow-tooltip prop="capitalRegistered" width="110">
        <template slot-scope="scope">
          <span>{{ moneyFormat(scope.row.capitalRegistered, 'w') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('注册资本币种')" align="center" prop="currency" show-overflow-tooltip width="110" :formatter="currencyFormat" />
      <el-table-column :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['company:client:view']"
            size="small"
            type="text"
            icon="el-icon-pie-chart"
            :title="$t('合作关系')"
            @click="relationHandle(scope.row)"
          />
          <el-button
            v-if="source === 'DEAL_EQUITY'"
            v-hasPermi="['company:account:edit']"
            size="small"
            type="text"
            icon="el-icon-bangzhu"
            :title="$t('管理账号')"
            @click="openAccount(scope.row)"
          />
          <el-button
            v-if="source === 'DEAL_EQUITY'"
            v-hasPermi="['company:account:remove']"
            :disabled="scope.row.userName === null || scope.row.userName === ''"
            size="small"
            type="text"
            icon="el-icon-switch-button"
            :title="$t('注销账号')"
            @click="delAccount(scope.row)"
          />
          <el-button
            v-hasPermi="['company:base:edit']"
            size="small"
            type="text"
            icon="el-icon-edit-outline"
            :title="$t('修改')"
            @click="updateHandle(scope.row)"
          />
          <el-button
            v-hasPermi="['company:base:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            :title="$t('删除')"
            @click="deleteHandle(scope.row)"
          />

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公司基本信息对话框 -->
    <el-dialog :title="$t('公司基本信息')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <companyBaseForm ref="companyBaseForm" />
    </el-dialog>
    <!-- 关系数据对话框 -->
    <el-dialog :title="$t('合作关系')" :visible.sync="relationFormOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <company-relation-tabs ref="companyRelationTabs" />
    </el-dialog>
    <!-- 开通账号对话框 -->
    <el-dialog :title="accountTitle" :visible.sync="accountFormOpen" :close-on-click-modal="false" style="height: 530px;" width="30%" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <el-form ref="ruleForm" v-loading="accountLoading" :model="accountForm" status-icon :rules="rulesAccount" class="demo-ruleForm">
        <el-form-item :label="$t('登陆名称')" prop="userName">
          <el-input v-model="accountForm.userName" :disabled="userDisable" :placeholder="$t('登陆名称')" show-word-limit maxlength="100" />
        </el-form-item>
        <el-form-item :label="$t('登陆密码')" prop="password">
          <el-input v-model="accountForm.password" type="password" autocomplete="off" :placeholder="$t('登陆密码')" show-word-limit maxlength="100" />
        </el-form-item>
        <el-form-item :label="$t('确认密码')" prop="confirmPassword">
          <el-input v-model="accountForm.confirmPassword" type="password" autocomplete="off" :placeholder="$t('确认密码')" show-word-limit maxlength="100" />
        </el-form-item>
        <el-form-item :label="$t('填报类型')" prop="dataType">
          <el-radio-group v-model="accountForm.dataType">
            <el-radio label="TB">{{ $t('填报') }}</el-radio>
            <el-radio label="SB">{{ $t('申报') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="float: right;">
          <el-button type="primary" @click="submitAccount">{{ $t('提交') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listDealTypeCompany, delCompanyBase } from '@/api/company/base/companyBase'
import companyBaseForm from './companyBaseForm.vue'
import { allFirstList } from '@/api/system/industry/sysIndustry'
import CompanyRelationTabs from '@/views/company/base/companyRelationTabs'
import { verifyThatTheAccountExists, delCompanyAccount, getByCompanyId, saveAccountUser } from '@/api/company/account/companyPortalAccount'
export default {
  components: {
    CompanyRelationTabs,
    companyBaseForm
  },
  data() {
    var checkPassword = (rule, value, callback) => {
      const that = this.accountForm
      if (!value) {
        return callback(new Error(this.$t('必填信息')))
      } else if (that.password !== that.confirmPassword) {
        callback(new Error(this.$t('两次密码不一致!')))
      } else {
        callback()
      }
    }
    var checkUserName = (rule, value, callback) => {
      const that = this.accountForm
      if (!value) {
        return callback(new Error(this.$t('必填信息')))
      } else if (that.userName.length < 6) {
        callback(new Error(this.$t('登陆名至少6位')))
      } else {
        if (this.userDisable) {
          callback()
        } else {
          verifyThatTheAccountExists(this.accountForm.userName).then(response => {
            if (!this.loginNameDisable) {
              if (response.code === 200) {
                if (response.data) {
                  callback()
                } else {
                  callback(new Error(this.$t('账号已存在!')))
                }
              } else {
                callback(new Error(this.$t('发生未知错误!')))
              }
            } else {
              callback()
            }
          })
        }
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 公司基本信息表格数据
      companyBaseList: [],
      // 是否显示弹出层
      formOpen: false,
      // 开通账号弹出层
      accountFormOpen: false,
      // 注册资本币种字典
      currencyOptions: [],
      // 实收资本币种字典
      actualCurrencyOptions: [],
      // 一级行业
      industryFirstOptions: [],
      // 查询参数
      queryParams: {
        companyName: undefined,
        companyShortName: undefined,
        industryFirst: undefined,
        industrySecond: undefined,
        dealStatus: undefined,
        companySource: this.$route.query.source,
        pageNum: 1,
        pageSize: 10
      },
      // 是否能删除
      whetherDel: false,
      // 关系数据弹出窗口
      relationFormOpen: false,
      // 表单参数
      form: {},
      // 数据来源
      source: this.$route.query.source,
      // 表单校验
      rules: {
        companyName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        companyShortName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        industryFirst: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        industrySecond: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        provinceRegistered: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        cityRegistered: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      industryFirstLabel: '',
      industrySecondLabel: '',
      // 开通账号加载
      accountLoading: false,
      // 用户名是否可修改
      userDisable: false,
      // 开通账号表单
      accountForm: {
        companyId: '',
        userName: '',
        password: '',
        confirmPassword: ''
      },
      rulesAccount: {
        userName: [{ validator: checkUserName,	trigger: 'blur' }],
        password: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        confirmPassword: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        dataType: [{ validator: checkPassword,	trigger: 'blur' }]
      },
      accountTitle: ''
    }
  },
  created() {
    // 获取所有的一级行业集合
    allFirstList().then(response => {
      this.industryFirstOptions = response.data
    })
    this.getDicts('currency').then(response => {
      this.currencyOptions = response.data
      this.actualCurrencyOptions = response.data
    })
    this.getList()
  },
  methods: {
    /** 查询公司基本信息列表 */
    getList() {
      this.loading = true
      listDealTypeCompany(this.queryParams).then(response => {
        this.companyBaseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 注册资本币种字典翻译
    currencyFormat(row) {
      return this.selectDictLabel(this.currencyOptions, row.currency)
    },
    // 实收资本币种字典翻译
    actualCurrencyFormat(row) {
      return this.selectDictLabel(this.actualCurrencyOptions, row.actualCurrency)
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        companyName: undefined,
        companyShortName: undefined,
        creditCode: undefined,
        legalPerson: undefined,
        administrativeArea: undefined,
        setDate: undefined,
        industryFirst: undefined,
        industrySecond: undefined,
        provinceRegistered: undefined,
        cityRegistered: undefined,
        detailsRegistered: undefined,
        capitalRegistered: undefined,
        currency: undefined,
        actualCapital: undefined,
        actualCurrency: undefined,
        logoInfo: undefined,
        tycId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.dealStatus = undefined
      this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
      this.formOpen = true
      this.$nextTick(() => {
        this.$refs.companyBaseForm.init(null)
        this.$refs.companyBaseForm.openLocation = 'companyList'
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.companyBaseForm.init(row)
        // this.$refs.companyBaseForm.openLocation = 'companyList'
      })
    },
    /** 删除按钮操作 */
    deleteHandle: async function(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delCompanyBase(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    exportHandle() {
      this.downLoadExcel('/company/companyBase/export', this.queryParams)
    },
    // 查看当前公司的关系数据
    relationHandle(row) {
      this.relationFormOpen = true
      this.$nextTick(() => {
        this.$refs.companyRelationTabs.view = this.$route.query.source
        this.$refs.companyRelationTabs.initData(row.id)
      })
    },
    // 表单重置
    resetAccount() {
      this.accountForm = {
        id: undefined,
        companyId: undefined,
        companyName: undefined,
        password: undefined,
        userName: undefined,
        confirmPassword: undefined,
        dataType: 'SB'
      }
    },
    // 开通企业填报账号
    openAccount(row) {
      this.resetAccount()
      this.accountForm.companyId = row.id
      this.accountForm.userName = row.companyName
      this.accountForm.companyName = row.companyName
      this.accountFormOpen = true
      this.accountLoading = true
      getByCompanyId(row.id).then(response => {
        if (response.code === 200) {
          if (response.data !== null) {
            console.log(response.data)
            this.$nextTick(() => {
              this.accountForm = response.data
              this.accountForm.dataType = response.data.dataType
              this.accountForm.password = ''
              this.userDisable = true
              this.accountTitle = this.$t('修改账户')
            })
          } else {
            this.userDisable = false
            this.accountTitle = this.$t('开通账户')
          }
        }
        this.accountLoading = false
      })
    },
    // 开通账户
    submitAccount() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.openAnAccountLoading = true
          saveAccountUser(this.accountForm).then(response => {
            if (response.code === 200) {
              this.accountFormOpen = false
              this.msgSuccess(this.$t('开通成功!'))
            } else {
              this.msgError(this.$t('保存异常'))
            }
            this.accountLoading = false
            this.getList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除账户
    delAccount(row) {
      this.$confirm(this.$t('是否注销账号?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delCompanyAccount(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('操作成功!'))
      })
    }
  }
}
</script>
